const { DataSystemDictDataModel } = require("../models/sys_dict_data");
const { DataSystemDictTypeModel } = require("../models/sys_dict_type");
const { fail, CODE, success } = require("../utils/utils");
const xlsx = require("node-xlsx");
class SystemDictTypeController {
  /**
   * @description 添加字典
   * @param {String} dict_name
   * @param {String} dict_type
   * @param {Number} status
   * @param {String} remark
   * @param {String} op_user_id
   */
  static async sysDictTypeAdd (ctx, next) {
    const { dict_name, dict_type, status = "1", remark } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!dict_name) {
        return (ctx.body = fail([], `请输入字典名称`, CODE.BUSINESS_ERROR));
      }
      const sysDictTypeInfo =
        await DataSystemDictTypeModel.findBySystemDictTypeName({ dict_name });
      if (sysDictTypeInfo) {
        return (ctx.body = fail([], `字典名称已存在`, CODE.BUSINESS_ERROR));
      }
      const sysDictTypeCodeInfo =
        await DataSystemDictTypeModel.findBySystemDictTypeCode({ dict_type });
      if (sysDictTypeCodeInfo) {
        return (ctx.body = fail([], `字典名称编码已存在`, CODE.BUSINESS_ERROR));
      }
      await DataSystemDictTypeModel.create({
        dict_name,
        dict_type,
        status,
        remark,
        op_user_id,
      });
      return (ctx.body = success([], `新增字典名称成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message));
    }
  }
  /**
   * @description 更新字典
   * @param {Number} dict_id
   * @param {String} dict_name
   * @param {String} dict_type
   * @param {Number} status
   * @param {String} remark
   * @param {String} op_user_id
   */
  static async sysDictTypeUpd (ctx, next) {
    const { dict_id, dict_name, dict_type, status, remark } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!dict_id) {
        return (ctx.body = fail([], `请输入必填项`, CODE.BUSINESS_ERROR));
      }
      const sysDictTypeInfo =
        await DataSystemDictTypeModel.findBySystemDictTypeNameNeId({
          dict_name,
          dict_id,
        });
      if (sysDictTypeInfo) {
        return (ctx.body = fail([], `字典已存在`, CODE.BUSINESS_ERROR));
      }
      const sysDictTypeCodeInfo =
        await DataSystemDictTypeModel.findBySystemDictTypeCodeId({
          dict_type,
          dict_id,
        });
      if (sysDictTypeCodeInfo) {
        return (ctx.body = fail([], `字典编码已存在`, CODE.BUSINESS_ERROR));
      }
      await DataSystemDictTypeModel.update({
        dict_id,
        dict_type,
        dict_name,
        status,
        remark,
        op_user_id,
      });
      return (ctx.body = success([], `字典更新成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 删除字典
   * @param {Number} dict_id
   */
  static async sysDictTypeDel (ctx, next) {
    const { dict_id } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!dict_id) {
        return (ctx.body = fail([], `dict_id 获取失败`, CODE.BUSINESS_ERROR));
      }
      await DataSystemDictTypeModel.delete({ op_user_id, dict_id });
      return (ctx.body = success([], `字典删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 批量删除字典
   * @param {Number} ids
   */
  static async sysDictTypeDelByIds (ctx, next) {
    const { ids } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return (ctx.body = fail([], `删除失败`, CODE.BUSINESS_ERROR));
      }
      await DataSystemDictTypeModel.deleteByIds({ op_user_id, ids });
      return (ctx.body = success([], `字典批量删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 字典分页列表
   * @param {String} dict_name
   * @param {String} dict_type
   * @param {String} status
   * @param {String} limit
   * @param {String} size
   */
  static async sysDictTypeList (ctx, next) {
    try {
      const { page_num, page_size, dict_name, dict_type, status } =
        ctx.request.query;
      let limit = Number(page_num) || 1;
      let size = Number(page_size) || 10;
      const { result, count } = await DataSystemDictTypeModel.list({
        limit,
        size,
        dict_name,
        dict_type,
        status,
      });
      return (ctx.body = success(
        { result, total: count[0].count },
        `获取字典数据成功`,
        CODE.SUCCESS
      ));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 字典所有列表
   */
  static async sysAllDictTypeList (ctx, next) {
    try {
      const { result } = await DataSystemDictTypeModel.all();
      return (ctx.body = success(result, `获取字典数据成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 通过字典id获取数据
   * @param {Number} dict_id
   */
  static async sysDictTypeById (ctx, next) {
    const { dict_id } = ctx.request.query;
    try {
      if (!dict_id) {
        return (ctx.body = fail([], `dict_id 获取失败`, CODE.BUSINESS_ERROR));
      }
      const result = await DataSystemDictTypeModel.findBySystemdDictTypeId({
        dict_id: Number(dict_id),
      });
      return (ctx.body = success(result, `获取字典数据成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 导出数据
   */
  static async sysDictTypeExport (ctx, next) {
    const { dict_name, dict_type, status } = ctx.request.body;
    try {
      const { result } = await DataSystemDictTypeModel.findList({
        dict_name,
        dict_type,
        status,
      });
      const sys_normal_disable_result =
        await DataSystemDictDataModel.findBySystemdDictType({
          dict_type: "sys_normal_disable",
        });
      let data = result.map((item) => {
        let current_staus = sys_normal_disable_result.find(
          (snd) => snd.dict_value === item.status
        );
        item.status = current_staus ? current_staus.dict_label : item.status;
        return item
      });
      const excelData = [
        ["字典编号", "字典名称", "状态", "备注", "创建时间"],
        ...data.map((item) => [
          item.dict_id,
          item.dict_name,
          item.status,
          item.remark,
          item.create_time,
        ]),
      ];
      const buffer = xlsx.build([{ name: "Sheet1", data: excelData }]);

      // 设置返回的http header信息，告诉浏览器该文件是一个excel文件
      ctx.set(
        "Content-Type",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      );
      ctx.set(
        "Content-Disposition",
        "attachment; filename=" + encodeURIComponent("字典数据.xlsx")
      );

      // 将生成的excel文件发送给客户端
      ctx.body = buffer;
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
}

module.exports = {
  SystemDictTypeController,
};
